package fr.sedoo.metadata.server.service.thesaurus;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import fr.sedoo.metadata.shared.domain.thesaurus.ThesaurusItem;

public class SingleLevelSkosHandler extends DefaultHandler {
	private static final String CONCEPT_NODE_NAME = "concept";
	private static final String LABEL_NODE_NAME = "preflabel";
	private static final String LANGUAGE_ATTRIBUTE_NAME = "xml:lang";
	private static final String ID_ATTRIBUTE_NAME = "rdf:about";

	private String language;
	private ThesaurusItem currentItem;
	private ArrayList<ThesaurusItem> result = new ArrayList<ThesaurusItem>();
	private boolean getValue = false;

	public SingleLevelSkosHandler(String language) {
		this.language = language;
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		if (qName.toLowerCase().endsWith(CONCEPT_NODE_NAME)) {
			currentItem = new ThesaurusItem();
			currentItem.setId(attributes.getValue(ID_ATTRIBUTE_NAME));
		} else if (qName.toLowerCase().endsWith(LABEL_NODE_NAME)) {
			String aux = attributes.getValue(LANGUAGE_ATTRIBUTE_NAME);
			if (language.compareToIgnoreCase(aux) == 0) {
				getValue = true;
			}
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		super.characters(ch, start, length);
		if (getValue) {
			currentItem.setValue(new String(ch, start, length));
			result.add(currentItem);
			getValue = false;
		}
	}

	public ArrayList<ThesaurusItem> getResult() {
		return result;
	}
}
